const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

function calcMatchScore(searchTerm, activityName) {
  searchTerm = String(searchTerm || '').toLowerCase();
  activityName = String(activityName || '').toLowerCase();

  const commonSubstrings = new Set();
  let totalScore = 0;

  for (let i = 0; i < searchTerm.length; i++) {
    for (let j = i + 1; j <= searchTerm.length; j++) {
      const sub = searchTerm.slice(i, j);
      if (activityName.includes(sub) && !commonSubstrings.has(sub)) {
        commonSubstrings.add(sub);
        const len = sub.length;
        totalScore += (len * (len + 1)) / 2;
      }
    }
  }
  return totalScore;
}

const ELEMENT_NUMBER = 15;

const querySearch = async (event) => {
  const search = String(event.searchTerms || '').trim();
  if (!search) return { activities: [] };

  const snapshot = await db.collection('Activity_Information')
    .where({
      Status: _.in(['Published', 'Withdraw'])
    })
    .get();

  if (!snapshot.data.length) return { activities: [] };

  const groupSnaps = await Promise.all(
    snapshot.data.map(async data => {
      try {
        return await db.collection('Activity_Group_Information')
          .where({ ActivityID: String(data._id) })
          .orderBy('GroupStartTime', 'asc')
          .get();
      } catch (e) {
        return { data: [] };
      }
    })
  );

  let activities = snapshot.data.map((data, idx) => {
    const groupSnap = groupSnaps[idx] || { data: [] };
    const score = calcMatchScore(search, data.ActivityName || '');

    if (score === 0) return null; // 匹配度为0直接忽略

    const activityTime = Array.isArray(groupSnap.data)
      ? groupSnap.data.map(g => ({
          startTime: g.GroupStartTime || null
        }))
      : [];

    return {
      activityID: String(data._id),
      activityName: data.ActivityName || '',
      activityImage: data.ActivityImageURL || '',
      activityStartTime: activityTime,
      activityLocation: data.ActivityLocation || '',
      score
    };
  }).filter(Boolean); // 过滤掉 score=0 的 null

  // 按匹配度排序
  activities.sort((a, b) => b.score - a.score);

  return { activities: activities.slice(0, ELEMENT_NUMBER) };
};

exports.main = async (event) => {
  return await querySearch(event);
};
